package offer;

import java.util.*;

/**
 * 描述:剑指 Offer 32 - III. 从上到下打印二叉树 III
 *
 * @author Madison You
 * @created 0:25
 */
public class Mid_32_2_LevelOrder {

    public static void main(String[] args) {
        TreeNode treeNode = CreateTreeNode.arrayToTreeNode(new Integer[]{3, 9, 20, null, null, 15, 7});
        new Mid_32_2_LevelOrder().levelOrder(treeNode);
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        ArrayList<List<Integer>> lists = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) return lists;
        queue.offer(root);
        boolean flag = true;
        while (!queue.isEmpty()) {
            ArrayList<Integer> integers = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                integers.add(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            if (flag) {
                lists.add(integers);
            } else {
                Collections.reverse(integers);
                lists.add(integers);
            }
            flag = !flag;
        }
        return lists;
    }
}
